package com.wushi.lenovo.asia5b.app_ui.home.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.camerakit.CameraKit;
import com.camerakit.CameraKitView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.mvp.base.BaseMvpActivity;
import com.mvp.utils.DisplayUtils;
import com.mvp.utils.ToastUtil;
import com.nanchen.compresshelper.CompressHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.other.mvpview.SnapActivityView;
import com.wushi.lenovo.asia5b.app_di.other.presenter.SnapActivityPresenter;
import com.wushi.lenovo.asia5b.app_ui.h5.SearchViewActivity;
import com.wushi.lenovo.asia5b.app_utils.WFileUtil;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;
import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/4/6.
 */
public class SnapActivity extends BaseMvpActivity<
        SnapActivityView, SnapActivityPresenter> implements SnapActivityView {
    @BindView(R.id.camera_snap)
    CameraKitView cameraKitView;
    @BindView(R.id.iv_snap_info)
    ImageView iv_snap_info;//提示
    @BindView(R.id.ll_snap_picture)
    LinearLayout ll_snap_picture;//上传相册
    @BindView(R.id.iv_snap_ok)
    ImageView iv_snap_ok;//拍照
    @BindView(R.id.iv_snap_change)
    ImageView iv_snap_change;//摄像头切换
    @BindView(R.id.view_snap_cover)
    View view_snap_cover;//封面图
    private PopupWindow popupWindow;

    @Override
    protected int getLayoutId() {
        setStatusTrans();
        return R.layout.activity_snap;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();

        initData();

        initEvent();
    }

    @Override
    protected void initView() {
        initWindow();
        cameraKitView.setPreviewEffect(CameraKit.PREVIEW_EFFECT_NEGATIVE);//预览效果
    }

    private void initWindow() {
        View popupView = View.inflate(this, R.layout.popup_snap_info, null);
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {

        iv_snap_change.setOnTouchListener(onTouchFacing);
        iv_snap_ok.setOnTouchListener(onTouchCaptureImage);
    }

    @OnClick({
            R.id.iv_snap_info,
            R.id.ll_snap_picture
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_snap_info:
                popupWindow.setFocusable(true);
                popupWindow.update();
                popupWindow.showAsDropDown(iv_snap_info,
                        0,
                        DisplayUtils.dip2px(this, 5));
                break;
            case R.id.ll_snap_picture: {
                EyeUtils.tagPermission();
                new RxPermissions(mActivity)
                        .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                PictureSelector.create(SnapActivity.this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles
                                        .previewImage(false)// 是否可预览图片
                                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                        .compress(true)// 是否压缩
                                        .openClickSound(false)// 是否开启点击声音
                                        .maxSelectNum(1)
                                        .forResult(CHOOSE_REQUEST);//结果回调onActivityResult code
                            } else {
                                ToastUtil.showToast(getString(R.string.permission_error1));
                            }
                        });

            }
            break;
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        cameraKitView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        cameraKitView.onResume();
    }

    @Override
    protected void onPause() {
        cameraKitView.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        cameraKitView.onStop();
        super.onStop();
    }


    //摄像头切换
    private View.OnTouchListener onTouchFacing = new View.OnTouchListener() {
        @Override
        public boolean onTouch(final View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_UP: {
                    view_snap_cover.setAlpha(0);
                    view_snap_cover.setVisibility(View.VISIBLE);
                    view_snap_cover.animate()
                            .alpha(1)
                            .setStartDelay(0)
                            .setDuration(300)
                            .setListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    super.onAnimationEnd(animation);
                                    int facing = cameraKitView.getFacing();
                                    if (facing == CameraKit.FACING_FRONT) {//前置摄像头
                                        cameraKitView.setFacing(CameraKit.FACING_BACK);
                                    } else {
                                        cameraKitView.setFacing(CameraKit.FACING_FRONT);
                                    }
//                                    cameraKitView.toggleFacing();

                                    view_snap_cover.animate()
                                            .alpha(0)
                                            .setStartDelay(200)
                                            .setDuration(300)
                                            .setListener(new AnimatorListenerAdapter() {
                                                @Override
                                                public void onAnimationEnd(Animator animation) {
                                                    super.onAnimationEnd(animation);
                                                    view_snap_cover.setVisibility(View.GONE);
                                                }
                                            })
                                            .start();
                                }
                            })
                            .start();
                    break;
                }
            }
            return true;
        }
    };

    //拍照
    private View.OnTouchListener onTouchCaptureImage = new View.OnTouchListener() {
        @Override
        public boolean onTouch(final View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    handleViewTouchFeedback(view, motionEvent);
//                    cameraKitView.onPause();
                    cameraKitView.captureImage(new CameraKitView.ImageCallback() {
                        @Override
                        public void onImage(CameraKitView cameraKitView, final byte[] jpeg) {
                            d("--->>>>>>>>---onImage");
                            imageCaptured(jpeg);
                        }
                    });
                    break;
                }

                case MotionEvent.ACTION_UP: {
                    handleViewTouchFeedback(view, motionEvent);
                    break;
                }
            }
            return true;
        }
    };

    public void imageCaptured(byte[] jpeg) {

        String imagePath = WFileUtil.createImagePath(this, "snap");
        File file = new File(imagePath);
        try {
            FileOutputStream outputStream = new FileOutputStream(imagePath);
            outputStream.write(jpeg);
            outputStream.close();
            d("--->>>>>>>>---imagePath:" + imagePath);
            File newFile = new CompressHelper.Builder(this)
                    .setMaxWidth(400)  // 默认最大宽度为720
                    .setMaxHeight(720) // 默认最大高度为960
                    .setQuality(50)    // 默认压缩质量为80
                    .setFileName("snap2") // 设置你需要修改的文件名
                    .setCompressFormat(Bitmap.CompressFormat.PNG) // 设置默认压缩为jpg格式
                    .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES).getAbsolutePath())
                    .build()
                    .compressToFile(file);
            d("--->>>>>>>>---newFile:" + newFile.getAbsolutePath());
            SearchViewActivity.startSearchViewActivityByImgpath(mActivity, newFile.getAbsolutePath());
            finish();

        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }

    boolean handleViewTouchFeedback(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                touchDownAnimation(view);
                return true;
            }

            case MotionEvent.ACTION_UP: {
                touchUpAnimation(view);
                return true;
            }

            default: {
                return true;
            }
        }
    }

    void touchDownAnimation(View view) {
        view.animate()
                .scaleX(0.88f)
                .scaleY(0.88f)
                .setDuration(300)
                .setInterpolator(new OvershootInterpolator())
                .start();
    }

    void touchUpAnimation(View view) {
        view.animate()
                .scaleX(1f)
                .scaleY(1f)
                .setDuration(300)
                .setInterpolator(new OvershootInterpolator())
                .start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        cameraKitView.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK)
            return;

        switch (requestCode) {

            case PictureConfig.CHOOSE_REQUEST: {
                // 图片选择
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList != null && selectList.size() > 0) {
                    LocalMedia localMedia = selectList.get(0);
                    String path = localMedia.getCompressPath();
                    if (!TextUtils.isEmpty(path)) {
                        SearchViewActivity.startSearchViewActivityByImgpath(mActivity, path);
                        finish();
                    }


                }
                break;
            }
        }
    }

}
